<template>
  <view class="glo-sidebar-filter">
    <!-- 筛选弹窗 -->
    <up-popup v-model:show="open" mode="right" @close="handlerClose">
      <view class="popup-wrap">
        <view class="popup-content">
          <up-form ref="filterRef" :labelStyle="{ fontSize: '26rpx', color: '#3D3D3D' }" :model="params"
            labelPosition="top" labelWidth="150">
            <up-form-item v-for="(item, index) in layout" :key="index" :label="item.label" :prop="item.prop">
              <glo-input v-model="params[item.key]" :placeholder="item.placeholder" :show-scan="item.type == 'scan'"
                :show-select="item.type == 'select'" @operation="(e) => handlerOperation(item, e)"></glo-input>
            </up-form-item>
          </up-form>
        </view>
        <view class="popup-footer">
          <sc-button height="60" type="grey-blue" width="187" @click="handlerReset">重置</sc-button>
          <sc-button height="60" type="primary" width="187" @click="bandlerFilter">筛选</sc-button>
        </view>
      </view>
    </up-popup>
    <!-- 商品大类选择器 -->
    <up-picker ref="productCategoryPickerRef" :columns="pickerData.productCategoryColumns"
      :show="pickerData.productCategoryShow" keyName="name" @cancel="pickerData.productCategoryShow = false"
      @confirm="handlerConfirm"></up-picker>

    <!-- 商品类别选择器 -->
    <up-picker ref="productSubcategoryPickerRef" :columns="pickerData.productSubcategoryColumns"
      :show="pickerData.productSubcategoryShow" keyName="name" @cancel="pickerData.productSubcategoryShow = false"
      @confirm="handlerConfirm"></up-picker>

    <!-- 手术类型选择器 -->
    <up-picker ref="surgeryTypePickerRef" :columns="pickerData.surgeryTypeColumns" :show="pickerData.surgeryTypeShow"
      keyName="name" @cancel="pickerData.surgeryTypeShow = false" @confirm="handlerConfirm"></up-picker>

    <!-- 选择仓库选择器 -->
    <up-picker ref="warehousePickerRef" :columns="pickerData.warehouseColumns" :show="pickerData.warehouseShow"
      keyName="name" @cancel="pickerData.warehouseShow = false" @confirm="handlerConfirm"></up-picker>

    <!-- 选择厂商选择器 -->
    <up-picker ref="manufacturerPickerRef" :columns="pickerData.manufacturerColumns" :show="pickerData.manufacturerShow"
      keyName="name" @cancel="pickerData.manufacturerShow = false" @confirm="handlerConfirm"></up-picker>

    <!-- 选择厂家-品牌选择器 -->
    <up-picker ref="manufacturerBrandPickerRef" :columns="pickerData.manufacturerBrandColumns"
      :show="pickerData.manufacturerBrandShow" keyName="name" @cancel="pickerData.manufacturerBrandShow = false"
      @change="handlerPickerChange" @confirm="handlerConfirm"></up-picker>
  </view>
</template>

<script setup>
import { CommonDropdown, DictEnum } from "@/commons/enums";
const props = defineProps({
  params: {
    type: Object,
    required: true,
  },
  show: {
    type: Boolean,
    required: true,
  },
  layout: {
    type: Array,
    required: true,
  },
});
const emit = defineEmits(["operation", "c", "filter", "reset"]);
const open = computed(() => {
  return props.show;
});

// 选择器数据
const pickerData = reactive({
  data: {},
  type: "",
  // 五个分类的show类型
  productCategoryShow: false, // 商品大类
  productSubcategoryShow: false, // 商品类别
  surgeryTypeShow: false, // 手术类型
  warehouseShow: false, // 选择仓库
  manufacturerShow: false, // 选择厂商
  manufacturerBrandShow: false, // 选择厂家-品牌
  // 五个分类的columns列表
  productCategoryColumns: [], // 商品大类数据
  productSubcategoryColumns: [], // 商品类别数据
  surgeryTypeColumns: [], // 手术类型数据
  warehouseColumns: [], // 选择仓库数据
  manufacturerColumns: [], // 选择厂商数据
  manufacturerBrandColumns: [], // 选择厂家-品牌数据
});

// 选择器引用
const productCategoryPickerRef = ref(null);
const productSubcategoryPickerRef = ref(null);
const surgeryTypePickerRef = ref(null);
const warehousePickerRef = ref(null);
const manufacturerPickerRef = ref(null);
const manufacturerBrandPickerRef = ref(null);

/**
 * 处理选择器变化事件（特殊处理厂家-品牌联动）
 * @param {Object} e 选择器变化事件对象
 */
const handlerPickerChange = (e) => {
  // 如果是第一列发生变化
  if (e.columnIndex === 0) {
    const selectedManufacturer = e.value[0];
    // 更新第二列数据为选中厂家的品牌列表
    manufacturerBrandPickerRef.value.setColumnValues(
      1,
      selectedManufacturer.commonCodeAndNameList || []
    );
    // 同时更新 pickerData 中的数据
    pickerData.manufacturerBrandColumns[1] =
      selectedManufacturer.commonCodeAndNameList || [];
  }
};

/**
 * 选择器确认回调
 * @param {Object} data 选择器数据
 */
const handlerConfirm = (data) => {
  console.log("🚀 >>> data:", data)
  pickerData.productCategoryShow = false;
  pickerData.productSubcategoryShow = false;
  pickerData.surgeryTypeShow = false;
  pickerData.warehouseShow = false;
  pickerData.manufacturerBrandShow = false;
  pickerData.manufacturerShow = false;
  props.params[pickerData.data.key] = data.value.map((item) => item.name).join("/");
};

// 筛选重置
const handlerReset = () => {
  props.layout.forEach((item) => {
    props.params[item.key] = undefined;
  });
  emit("update:show", false);
  emit("reset");
};

/**
 * 关闭筛选选择器
 */
const handlerClose = () => {
  pickerData.productCategoryShow = false;
  pickerData.productSubcategoryShow = false;
  pickerData.surgeryTypeShow = false;
  pickerData.warehouseShow = false;
  pickerData.manufacturerBrandShow = false;
  pickerData.manufacturerShow = false;
  emit("update:show", false);
}



// 筛选
const bandlerFilter = () => {
  emit("update:show", false);
  emit("filter");
};

/**
 * 打开筛选选择器
 * @param {String} type 选择器类型
 */
const openSelect = (type) => {
  console.log("🚀 type", type);
  switch (type) {
    case "productCategory": // 商品大类
      if (pickerData.productCategoryColumns.length > 0) {
        pickerData.productCategoryShow = true;
      } else {
        _api.getCommonList(DictEnum.PRODUCT_CATEGORY).then((res) => {
          pickerData.productCategoryShow = true;
          pickerData.productCategoryColumns = [res];
        });
      }
      break;
    case "productSubcategory": // 商品小类
      // 如果已经有数据，直接显示选择器
      if (pickerData.productSubcategoryColumns.length > 0) {
        pickerData.productSubcategoryShow = true;
      } else {
        // 否则请求数据
        _api.getCommonList(DictEnum.PRODUCT_SUBCATEGORY).then((res) => {
          pickerData.productSubcategoryShow = true;
          pickerData.productSubcategoryColumns = [res];
        });
      }
      break;
    case "surgeryType": // 手术类型
      // 如果已经有数据，直接显示选择器
      if (pickerData.surgeryTypeColumns.length > 0) {
        pickerData.surgeryTypeShow = true;
      } else {
        // 否则请求数据
        _api.getCommonList(DictEnum.SURGERY_TYPE).then((res) => {
          pickerData.surgeryTypeShow = true;
          pickerData.surgeryTypeColumns = [res];
        });
      }
      break;
    case "warehouseName": // 仓库名称
      // 如果已经有数据，直接显示选择器
      if (pickerData.warehouseColumns.length > 0) {
        pickerData.warehouseShow = true;
      } else {
        // 否则请求数据
        _api
          .getCommonCodeAndNameByType({ type: CommonDropdown.WAREHOUSE })
          .then((res) => {
            pickerData.warehouseShow = true;
            pickerData.warehouseColumns = [res];
          });
      }
      break;
    case "manufacturer": // 厂家
      if (pickerData.manufacturerColumns.length > 0) {
        pickerData.manufacturerShow = true;
      } else {
        // 否则请求数据
        _api
          .getCommonCodeAndNameByType({ type: CommonDropdown.MANUFACTURER })
          .then((res) => {
            pickerData.manufacturerShow = true;
            pickerData.manufacturerColumns = [res];
          });
      }
      break;
    case "manufacturerName": // 厂家-品牌
      // 如果已经有数据，直接显示选择器
      if (pickerData.manufacturerBrandColumns.length > 0) {
        pickerData.manufacturerBrandShow = true;
      } else {
        // 否则请求数据
        _api
          .getCommonCodeAndNameByType({
            type: CommonDropdown.MANUFACTURER_BRAND,
          })
          .then((res) => {
            pickerData.manufacturerBrandShow = true;
            pickerData.manufacturerBrandColumns = [
              res,
              res[0].commonCodeAndNameList,
            ];
          });
      }
      break;
  }
};
const handlerOperation = (item, e) => {
  pickerData.data = item;
  if (item.type === "select") {
    openSelect(item.key);
    return;
  }
  emit("operation", item, e);
};
</script>

<style lang="scss" scoped>
.popup-wrap {
  position: relative;
  padding-top: calc(env(safe-area-inset-top) + 44px);
  width: 525rpx;
  height: 100%;

  .popup-content {
    padding: 60rpx 35rpx;
  }

  .popup-footer {
    position: absolute;
    bottom: 78rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 45rpx;
    width: 100%;
  }

  .popup-title {
    color: #3d3d3d;
    font-weight: 400;
    font-size: 26rpx;
    font-family: Alibaba PuHuiTi 2, Alibaba PuHuiTi 20;
    line-height: 26rpx;
  }
}
</style>
